package com.thinktank.frontcontroller;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.thinktank.controller.*;

//@WebServlet("*.do")

public class MyFrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private List<String> cmds = new ArrayList<String>();
	private List<Controller> ctrls = new ArrayList<Controller>();

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		// 컨트롤러 업로드
		String real = config.getServletContext().getRealPath("");
		String path = config.getInitParameter("path");

		FileInputStream fis;

		try {
			fis = new FileInputStream(real + path);
			Scanner scanner = new Scanner(fis);
			while (scanner.hasNext()) {
				String[] temp = scanner.nextLine().split(",");
				cmds.add(temp[0]);
				Controller ctrl = (Controller) Class.forName(temp[1])
						.newInstance();
				ctrls.add(ctrl);
				// System.out.println(temp[0] + " : " + temp[1]); //등록된 컨트롤러 보기
			}
			scanner.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = requestURI.substring(contextPath.length());
		System.out.println("command : " +command);

		Controller controller = null;
		for (int i = 0; i < cmds.size(); i++) {
			if (command.equals(cmds.get(i))) {
				controller = ctrls.get(i);
				break;
			}
		}
		if (controller == null)
			System.out.println(command + " - 해당 컨트롤러가 없습니다.");

		// 받은 command로 controller 선택

		String result = controller.execute(request, response);
		String[] rs_splt = result.split(":");
		if (rs_splt[0].equals("redirect")){
			response.sendRedirect(rs_splt[1]);
		}
		else {
			System.out.println(result);
			RequestDispatcher dispatcher = request.getRequestDispatcher(result);
			dispatcher.forward(request, response);
		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		service(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		service(req, resp);
	}

}
